package cn.com.dhcc.turbo.service.registry;

import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import cn.com.dhcc.app.core.CM;
import cn.com.dhcc.app.core.dao.CrudDao;
import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.cachehandler.CacheHandler.CacheOperType;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.AbstractCrudService;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.tag.CommonStaticCode.SUCCESSFAIL;
import cn.com.dhcc.app.core.tag.CommonStaticCode.YESNO;
import cn.com.dhcc.app.core.util.RegUtil;
import cn.com.dhcc.app.pub.core.consts.AppIocBean;
import cn.com.dhcc.app.pub.core.consts.NodeInfoParam;
import cn.com.dhcc.app.pub.core.service.TurboCacheService;
import cn.com.dhcc.app.pub.core.tag.AppTagEl;
import cn.com.dhcc.turbo.dao.registry.NodeInfoDao;
import cn.com.dhcc.turbo.entity.exch.GapOwnerConf;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.registry.SynchronizeInfo.SyncOperType;
import cn.com.dhcc.turbo.entity.registry.SynchronizeInfo.SyncType;
import cn.com.dhcc.turbo.service.registry.sync.ISyncSender;
import cn.com.dhcc.turbo.service.registry.sync.SynchronizeHandler;
import cn.com.dhcc.turbo.service.registry.vo.RegistResult;
import cn.com.dhcc.turbo.service.sysmgr.UserMgrService;

/**
 * 节点信息service
 * 
 * @日期：2014-5-12 上午11:33:03
 * @作者：张洪涛
 * @版权所有：东华软件
 * @版本：1.0
 */
@Service
public class NodeInfoService extends AbstractCrudService<NodeInfo> {
	@Autowired
	@Qualifier(AppIocBean.TURBO_CACHE_SERVICE)
	private TurboCacheService turboCacheService;
	@Autowired
	private NodeInfoDao nodeInfoDao;
	@Autowired
	@Qualifier(AppIocBean.SYNC_SENDER_RMI_IMPL)
	private ISyncSender syncSender;
	@Autowired
	SynchronizeHandler synchronizeHandler;
	@Autowired
	UserMgrService userMgrService;
	@Autowired
	SzyFeatureMgr nodePermissionService;
	

	@SuppressWarnings("deprecation")
	Logger ftpLogger = Log.getDetachLogger(LOGTYPE.FTP);
	@SuppressWarnings("deprecation")
	Logger syslogger = Log.getDetachLogger(LOGTYPE.SYS);

	public NodeInfo getNodeInfoByNodeCode(String nodeCode) throws ServiceException {
		try {
			return nodeInfoDao.getNodeInfoByNodeCode(nodeCode);
		} catch (DaoException e) {
			throw new ServiceException("获取节点信息列表失败", e);
		}
	}

	/**
	 * 获取节点信息列表
	 * @param pager
	 * @param condition
	 * @return
	 * @throws ServiceException
	 */
	public PagerData<NodeInfo> list(Pager pager, WhereCondition condition) throws ServiceException {
		try {
			return nodeInfoDao.list(pager, condition);
		} catch (DaoException e) {
			throw new ServiceException("获取节点信息列表失败", e);
		}
	}

	/**
	 * 修改节点信息
	 * @param vo
	 * @throws ServiceException
	 * @throws NiceException 
	 */
	public int updateAndSync(NodeInfo vo) throws ServiceException, NiceException {
		try {
			int r = super.update(vo);
			turboCacheService.updateNodeCache(CacheOperType.UPDATE, vo);
			try {
				synchronizeHandler.syncToAllNodesFromLocalNode(SyncType.NODE_INFO, false, vo, SyncOperType.UPDATE,true);
			} catch (Exception e) {
				//同步出错，仍然可以进行其他操作
				throw new NiceException("节点修改成功，但信息同步失败，请手动同步..");
			}
			return r;
		} catch (ServiceException e) {
			throw new ServiceException("修改节点失败", e);
		}
	}
	/**
	 * 注册节点信息
	 * @param vo
	 * @throws ServiceException
	 * @throws NiceException 
	 */
	public void insertAndSync(NodeInfo vo) throws ServiceException, NiceException {
		//网络类型不相同，无法进行握手处理，只需要同步即可
		if(!vo.getNetType().equals(NodeInfoParam.NODE_NET_TYPE)){
			try {
				nodeInfoDao.insert(vo);
				synchronizeHandler.syncToAllNodes(SyncType.NODE_INFO, false, vo,vo, vo, SyncOperType.INSERT,true);
				turboCacheService.updateNodeCache(CacheOperType.UPDATE, vo);
			} catch (DaoException e) {
				throw new ServiceException(e);
			}
		}else{
			RegistResult registResult =  nodePermissionService.registNode(vo);
			if(registResult.getResult()==SUCCESSFAIL.SUCCESS){
				turboCacheService.updateNodeCache(CacheOperType.UPDATE, vo);
			}else{
				throw new NiceException(registResult.getMsg());
			}
		}
	}

	/**
	 * 删除节点
	 * @param id
	 * @throws ServiceException
	 */
	public int delete(String id) throws ServiceException {
		try {
			NodeInfo nodeInfo = get(id);
			if (nodeInfo != null) {
				nodeInfo.setStatus(YESNO.NO.getStatus());
				return update(nodeInfo);
			} else {
				throw new ServiceException("删除节点失败,节点不存在");
			}
		} catch (ServiceException e) {
			throw new ServiceException("删除节点失败", e);
		}

	}

	public int getMaxNodeCode(String str) throws ServiceException {
		try {
			return nodeInfoDao.getMaxNodeCode(str);
		} catch (DaoException e) {
			throw new ServiceException("获取最大节点编码失败", e);
		}
	}

	/**
	 * 验证节点名称唯一性
	 * @param name
	 * @param checkStr
	 * @return
	 * @throws ServiceException
	 */
	public boolean checkNodeName(String name, String checkStr) throws ServiceException {
		try {
			return nodeInfoDao.checkNodeName(name, checkStr);
		} catch (DaoException e) {
			throw new ServiceException("验证节点名称唯一性失败", e);
		}
	}

	public int batchDelete(String[] ids) throws ServiceException {
		try {
			return nodeInfoDao.batchDelete(ids);
		} catch (DaoException e) {
			throw new ServiceException("验证节点名称唯一性失败", e);
		}
	}

	/**
	 * 获取Root节点
	 * @return
	 * @throws ServiceException
	 */
	public NodeInfo getRootNodeInfo() throws ServiceException {
		try {
			return nodeInfoDao.getRootNodeInfo();
		} catch (DaoException e) {
			throw new ServiceException("获取Root节点失败", e);
		}
	}

	/**
	 * 获取除根节点外全部节点
	 * @return
	 * @throws ServiceException
	 */
	public List<NodeInfo> getAllList() throws ServiceException {
		try {
			return nodeInfoDao.getAllNodeList();
		} catch (DaoException e) {
			throw new ServiceException("获取全部节点失败", e);
		}
	}

	/**
	 * 获取本地节点
	 * @return
	 * @throws ServiceException
	 */
	public NodeInfo getLocalNode() throws ServiceException {
		try {
			return nodeInfoDao.getLocalNode();
		} catch (DaoException e) {
			throw new ServiceException("获取本地节点失败", e);
		}
	}
	/**
	 * 验证同步地址是否已经存在
	 * @return
	 * @throws ServiceException
	 */
	public boolean isSyncUrlExist(String syncUrl) throws ServiceException {
		try {
			return nodeInfoDao.isSyncUrlExist(syncUrl);
		} catch (DaoException e) {
			throw new ServiceException("验证同步地址是否已经被其他节点占用", e);
		}
	}
	public List<NodeInfo> getAllNodeList() throws ServiceException {
		try {
			return nodeInfoDao.getAllNodeList();
		} catch (DaoException e) {
			throw new ServiceException("获取全部节点失败", e);
		}
	}

	public NodeInfo getNodeInfoBySysId(String sysId) throws ServiceException {
		String sql = "select n.*  from " + SI_TABLE("turbo_node_info") + " n ," + SI_TABLE("turbo_sys_info")
				+ " s where s.node_id=n.id and s.id=?";
		try {
			return CM.getDao().getModule("根据系统id获取系统所属节点", sql, NodeInfo.class, new Object[] { sysId });
		} catch (DaoException e) {
			throw new ServiceException("根据系统id获取系统所属节点", e);
		}
	}

	/**
	 * 添加同步过来的节点
	 * @param remoteNode
	 * @return
	 * @throws ServiceException 
	 */
	public int insertOrUpdateRemoteNode(NodeInfo remoteNode) throws ServiceException {
		int r = super.insertOrUpdate(remoteNode);
		turboCacheService.updateNodeCache(CacheOperType.UPDATE, remoteNode);
		return r;
	}

	public void initNodeInfo() throws NiceException, ServiceException {
		/*if(NodeInfoParam.isMwr()){
			//如果根节点没有初始化则初始化
			boolean exist = nodeExitsByRegionCode(NodeInfoParam.ROOT_NODEREGION_CODE);
			if(!exist){
				NodeInfo mwrNode = new NodeInfo();
				String nodeId = UUIDGenerator.getUUID();
				mwrNode.setId(nodeId);
				mwrNode.setInstallUrl(NetUtil.getLocalHostIp()+":"+RmiServerInitListener.rmiServerPort);
				mwrNode.setIsLocal(YESNO.YES.getStatus());
				mwrNode.setMtime(new Date());
				mwrNode.setNodeCode(NodeInfoParam.MWR_NODEREGION_CODE+NodeInfoParam.NODE_NET_TYPE+"00");
				mwrNode.setNodeName(NodeInfoParam.MWR_NODE_NAME);
				mwrNode.setPid(NodeInfoParam.MWR_NODE_PID);
				mwrNode.setStatus(YESNO.YES.getStatus());
				mwrNode.setHasGap(NodeInfoParam.hasGap);
				mwrNode.setAdminEmail(NodeInfoParam.MWR_NODE_ADMIN_EMAIL);
				insert(mwrNode);
				//初始化节点管理员
			}
		}*/
		checkNodeInitInfo();
		try {
			NodeInfo localNodeInfo = nodeInfoDao.getLocalNode();
			if(localNodeInfo == null){
				userMgrService.createLocalAdminUser(NodeInfoParam.MWR_NODE_ADMIN_EMAIL);
			}
			
		} catch (DaoException e) {
			syslogger.error("创建节点管理员账号失败...!");
		}
		
		
		syslogger.info("创建节点管理员账号成功...!");
	}

	private void checkNodeInitInfo() throws NiceException {
		try {
			//验证是否是管理节点配置的修改。同一行政区只能有一个管理节点
			String nodeRegon = NodeInfoParam.NODE_REGION_CODE;
			
			String netType = NodeInfoParam.NODE_NET_TYPE;
			NodeInfo localNodeInfo = nodeInfoDao.getLocalNodeNoNetType();
			if(localNodeInfo==null){
				checkIfExitsAMgrNodeWithSameRegionCode(nodeRegon);
				return;
			}
			//验证网络类型，时候有修改，不允许修改
			if(!localNodeInfo.getNetType().equalsIgnoreCase(netType))throw new NiceException("节点网络类型配置和数据库原有不一致，原有为["+localNodeInfo.getNetType()+"]");
		    //验证本地节点行政区编码是否被修改过
			String dbRegon = localNodeInfo.getNodeCode().substring(0, 6);
			if(!dbRegon.equalsIgnoreCase(nodeRegon))throw new NiceException("节点行政区编码配置和数据库原有不一致，原有为["+dbRegon+"]");
			//验证同步地址：同步地址修改后需要同步
			/*String installUrl = localNodeInfo.getInstallUrl();
			String syncUrl = NodeInfoParam.getSyncUrl();
			if(!installUrl.equalsIgnoreCase(syncUrl)){
				syslogger.warn("同步地址发生改变，原来为："+installUrl+",现在为："+syncUrl);
				try {
					updateAndSync(localNodeInfo);
				} catch (ServiceException e) {
					syslogger.error(e);
				}
			}*/
		} catch (DaoException e) {
			throw new NiceException(e);
		}
		
	}

	private void checkIfExitsAMgrNodeWithSameRegionCode(String nodeRegon) throws NiceException {
		String sql = "select count(*) from " + SI_TABLE("turbo_node_info")+" n where node_code like ?";
		String isMgr = YESNO.YES.getStatus();
		try {
			int num = CM.getDao().queryForInt("获取",sql,new Object[]{nodeRegon+isMgr});
			if(num>0)throw new NiceException("统一行政区编码下只能有一个管理节点!");
		} catch (DaoException e) {
			throw new NiceException("验证节点编码失败");
		}
		
	}

	public boolean checkServerUrl(String nodeInstallUrl)  {
		return syncSender.syncUrlIsValid(nodeInstallUrl);
	}

	/**
	 * 验证节点编码
	 * @param confNodeCode
	 * @throws NiceException 
	 */
	@SuppressWarnings("unused")
	private void checkNodeCode(String confNodeCode) throws NiceException {
		//是否编码规则 PPRRCC X NN
		if (!RegUtil.match(confNodeCode, "\\d{6}[01]\\d{2}")) {
			throw new NiceException("本地节点编码[" + confNodeCode + "]验证失败，请检查配置文件");
		}
		try {
			NodeInfo beUesdNode = nodeInfoDao.ifNodeCodeIsUesedByNotLocalNode(confNodeCode);
			if (beUesdNode != null) {
				throw new NiceException("本地节点编码[" + confNodeCode + "]验证失败，编码已被节点[" + beUesdNode.getNodeName() + "]占用");
			}
		} catch (DaoException e) {
			throw new NiceException("本地节点编码[" + confNodeCode + "]验证失败，系统异常");
		}
		//验证编码是否已经被远程节点占用
	}

	@Override
	public CrudDao<NodeInfo> getCrudDao() {
		return nodeInfoDao;
	}

	/**
	 * 获取节点树,根节点和根节点的子节点
	 * @param isLocal 是否以本地节点为根节点　true 本地节点    false 水利部　
	 * @param isAll　是否为全部节点　true 全部节点　false 管理范围内节点
	 * @return
	 * @throws ServiceException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String getRootNodeTree(boolean isLocal, boolean isAll) throws ServiceException {
		StringBuffer nodeTreeData = new StringBuffer();
		try {
			//为每个节点增加添加　修改　属性，用于确定单击节点时显示权限　　isAdd：注册权限　isEdit：修改　netType：网络类型
			NodeInfo localNode = nodeInfoDao.getLocalNode();
//			NodeInfo localDummyNode = nodeInfoDao.getLocalDummyNode("1".equals(NodeInfoParam.NODE_NET_TYPE)? "2" : "1");
			NodeInfo root = nodeInfoDao.getRootNodeInfoByPidAndNetType(NodeInfoParam.MWR_NODE_PID,NodeInfoParam.NODE_NET_TYPE);
//			NodeInfo otherRoot = nodeInfoDao.getRootNodeInfoByPidAndNetType(NodeInfoParam.MWR_NODE_PID,"1".equals(NodeInfoParam.NODE_NET_TYPE)? "2" : "1");
			nodeTreeData.append("[");
			nodeTreeData.append("{");
			nodeTreeData.append("id:'").append(NodeInfoParam.NODE_NET_TYPE).append("',");
			nodeTreeData.append("pId:'").append("").append("',");
			nodeTreeData.append("name:'").append(AppTagEl.ctname("NET_TYPE", NodeInfoParam.NODE_NET_TYPE)).append("',");
			nodeTreeData.append("orgCode:'").append("").append("',");
			nodeTreeData.append("isAdd:'").append("0").append("',");
			nodeTreeData.append("netType:'").append(NodeInfoParam.NODE_NET_TYPE).append("',");
			nodeTreeData.append("isEdit:'").append("0").append("',");
			nodeTreeData.append("nocheck:").append(true).append(",");
			nodeTreeData.append("checked:").append(false).append(",");
			nodeTreeData.append("icon:").append("_rs_image_path+\'/1_open.png'").append(",");
			nodeTreeData.append("open:").append(true);
			nodeTreeData.append("}");
//			
//			nodeTreeData.append(",{");
//			nodeTreeData.append("id:'").append("1".equals(NodeInfoParam.NODE_NET_TYPE)? "2" : "1").append("',");
//			nodeTreeData.append("pId:'").append("").append("',");
//			nodeTreeData.append("name:'").append(AppTagEl.ctname("NET_TYPE", "1".equals(NodeInfoParam.NODE_NET_TYPE)? "2" : "1")).append("',");
//			nodeTreeData.append("orgCode:'").append("").append("',");
//			nodeTreeData.append("netType:'").append("1".equals(NodeInfoParam.NODE_NET_TYPE)? "2" : "1").append("',");
//			if(NodeInfoParam.isManaagerNode() && NodeInfoParam.isMwr()){
//				nodeTreeData.append("isAdd:'").append("1").append("',");
//			}else{
//				if(localDummyNode != null && otherRoot != null){
//					nodeTreeData.append("isAdd:'").append("1").append("',");
//				}else{
//					nodeTreeData.append("isAdd:'").append("0").append("',");
//				}
//			}
//			nodeTreeData.append("isEdit:'").append("0").append("',");
//			nodeTreeData.append("nocheck:").append(true).append(",");
//			nodeTreeData.append("checked:").append(false).append(",");
//			nodeTreeData.append("icon:").append("_rs_image_path+\'/1_close.png'").append(",");
//			nodeTreeData.append("open:").append(true);
//			nodeTreeData.append("}");
			
			//真实节点数据
			nodeTreeData.append(",{");
			nodeTreeData.append("id:'").append(root.getId()).append("',");
			nodeTreeData.append("pId:'").append(NodeInfoParam.NODE_NET_TYPE).append("',");
			nodeTreeData.append("name:'").append(root.getNodeName()).append("',");
			if (!root.getId().equals(localNode.getId()) && !root.getPid().equals(localNode.getId())) {
				nodeTreeData.append("font:").append("{'color':'grey'}").append(",");
				nodeTreeData.append("isEdit:'").append("0").append("',");
			} else {
				nodeTreeData.append("font:").append("{'color':'#428bca'}").append(",");
				if(NodeInfoParam.isManaagerNode()){
					nodeTreeData.append("isEdit:'").append("1").append("',");
				}
			}
			nodeTreeData.append("orgCode:'").append(root.getNodeCode().substring(0, 6)).append("',");
			nodeTreeData.append("netType:'").append(root.getNetType()).append("',");
			if ( root.getId().equals(localNode.getId()) && NodeInfoParam.isManaagerNode()) {
				nodeTreeData.append("isAdd:'").append("1").append("',");
			} else {
				nodeTreeData.append("isAdd:'").append("0").append("',");
			}
			nodeTreeData.append("nocheck:").append(true).append(",");
			nodeTreeData.append("checked:").append(false).append(",");
			if (root.getIsLocal().equals("1")) {
				nodeTreeData.append("icon:").append("_rs_image_path+\'/node1.png'").append(",");
			} else if (root.getPid().equals(localNode.getId())) {
				nodeTreeData.append("icon:").append("_rs_image_path+\'/node2.png'").append(",");
			}else{
				nodeTreeData.append("icon:").append("_rs_image_path+\'/node0.png'").append(",");
			}
			nodeTreeData.append("open:").append(true);
			nodeTreeData.append("}");
			
			List list = nodeInfoDao.getAllList(root.getId());
			
			for (Iterator<NodeInfo> iterator = list.iterator(); iterator.hasNext();) {
				NodeInfo vo = iterator.next();
				boolean checked = false;
				boolean isOpen = false;
//				boolean noCheck = true;
				boolean isParent = false;
				if (Integer.parseInt(vo.getCont()) > 0 && isAll) {
					isParent = true;
				}
				nodeTreeData.append(",");
				nodeTreeData.append("{");
				nodeTreeData.append("id:'").append(vo.getId()).append("',");
				nodeTreeData.append("pId:'").append(vo.getPid()).append("',");
				nodeTreeData.append("name:'").append(vo.getNodeName()).append("',");
				if ( !vo.getPid().equals(localNode.getId())) {
					nodeTreeData.append("font:").append("{'color':'grey'}").append(",");
					nodeTreeData.append("isEdit:'").append("0").append("',");
				} else {
					nodeTreeData.append("font:").append("{'color':'#428bca'}").append(",");
					if(NodeInfoParam.isManaagerNode()){
						nodeTreeData.append("isEdit:'").append("1").append("',");
					}
				}
				nodeTreeData.append("orgCode:'").append(vo.getNodeCode().substring(0, 6)).append("',");
				nodeTreeData.append("netType:'").append(vo.getNetType()).append("',");
				if ( vo.getId().equals(localNode.getId()) && NodeInfoParam.isManaagerNode()) {
					nodeTreeData.append("isAdd:'").append("1").append("',");
				} else {
					nodeTreeData.append("isAdd:'").append("0").append("',");
				}
				nodeTreeData.append("type:'").append(1).append("',");
				nodeTreeData.append("nocheck:").append(true).append(",");
				nodeTreeData.append("checked:").append(checked).append(",");
				nodeTreeData.append("open:").append(isOpen).append(",");
				if (vo.getIsLocal().equals("1")) {
					nodeTreeData.append("icon:").append("_rs_image_path+\'/node1.png'").append(",");
				} else if (vo.getPid().equals(localNode.getId())) {
					nodeTreeData.append("icon:").append("_rs_image_path+\'/node2.png'").append(",");
				}else{
					nodeTreeData.append("icon:").append("_rs_image_path+\'/node0.png'").append(",");
				}
				nodeTreeData.append("isParent:").append(isParent);
				nodeTreeData.append("}");
			}
			
			//虚拟节点，不同网段
//			if(otherRoot != null){
//				nodeTreeData.append(",{");
//				nodeTreeData.append("id:'").append(otherRoot.getId()).append("',");
//				nodeTreeData.append("pId:'").append("1".equals(NodeInfoParam.NODE_NET_TYPE)? "2" : "1").append("',");
//				nodeTreeData.append("name:'").append(otherRoot.getNodeName()).append("',");
//				if (localDummyNode != null && !otherRoot.getId().equals(localDummyNode.getId()) && !otherRoot.getPid().equals(localDummyNode.getId())) {
//					nodeTreeData.append("font:").append("{'color':'grey'}").append(",");
//					nodeTreeData.append("icon:").append("_rs_image_path+\'/node0.png'").append(",");
//				} else {
//					nodeTreeData.append("font:").append("{'color':'#428bca'}").append(",");
//					nodeTreeData.append("icon:").append("_rs_image_path+\'/node2.png'").append(",");
//				}
//				nodeTreeData.append("orgCode:'").append(otherRoot.getNodeCode().substring(0, 6)).append("',");
//				nodeTreeData.append("netType:'").append(otherRoot.getNetType()).append("',");
//				if(NodeInfoParam.isManaagerNode() && NodeInfoParam.isMwr()){
//					nodeTreeData.append("isAdd:'").append("1").append("',");
//					nodeTreeData.append("isEdit:'").append("1").append("',");
//				}else{
//					if(localDummyNode != null ){
//						nodeTreeData.append("isAdd:'").append("1").append("',");
//					}else{
//						nodeTreeData.append("isAdd:'").append("0").append("',");
//					}
//					nodeTreeData.append("isEdit:'").append("0").append("',");
//				}
//				
//				nodeTreeData.append("nocheck:").append(true).append(",");
//				nodeTreeData.append("checked:").append(false).append(",");
//				nodeTreeData.append("open:").append(false);
//				nodeTreeData.append("}");
//				List otherList = nodeInfoDao.getAllList(otherRoot.getId());
//				for (Iterator<NodeInfo> iterator = otherList.iterator(); iterator.hasNext();) {
//					NodeInfo vo = iterator.next();
//					boolean checked = false;
//					boolean isOpen = false;
//					boolean noCheck = true;
//					boolean isParent = false;
//					if (Integer.parseInt(vo.getCont()) > 0 && isAll) {
//						isParent = true;
//					}
//					nodeTreeData.append(",");
//					nodeTreeData.append("{");
//					nodeTreeData.append("id:'").append(vo.getId()).append("',");
//					nodeTreeData.append("pId:'").append(vo.getPid()).append("',");
//					nodeTreeData.append("name:'").append(vo.getNodeName()).append("',");
//					nodeTreeData.append("orgCode:'").append(vo.getNodeCode().substring(0, 6)).append("',");
//					nodeTreeData.append("netType:'").append(vo.getNetType()).append("',");
//					if(NodeInfoParam.isManaagerNode() && NodeInfoParam.isMwr()){
//						nodeTreeData.append("isAdd:'").append("1").append("',");
//					}else{
//						if(localDummyNode != null ){
//							nodeTreeData.append("isAdd:'").append("1").append("',");
//						}else{
//							nodeTreeData.append("isAdd:'").append("0").append("',");
//						}
//					}
//					
//					if(localDummyNode != null && vo.getPid().equals(localDummyNode.getId())){
//						nodeTreeData.append("font:").append("{'color':'#428bca'}").append(",");
//						nodeTreeData.append("icon:").append("_rs_image_path+\'/node2.png'").append(",");
//						nodeTreeData.append("isEdit:'").append("1").append("',");
//					}else{
//						nodeTreeData.append("font:").append("{'color':'grey'}").append(",");
//						nodeTreeData.append("icon:").append("_rs_image_path+\'/node0.png'").append(",");
//						nodeTreeData.append("isEdit:'").append("0").append("',");
//					}
//					
//					nodeTreeData.append("type:'").append(1).append("',");
//					nodeTreeData.append("nocheck:").append(true).append(",");
//					nodeTreeData.append("checked:").append(checked).append(",");
//					nodeTreeData.append("open:").append(isOpen).append(",");
//					nodeTreeData.append("isParent:").append(isParent);
//					nodeTreeData.append("}");
//				}
//				
//			}
		} catch (DaoException e) {
			throw new ServiceException("获取节点树失败", e);
		}
		nodeTreeData.append("]");
		return nodeTreeData.toString();
	}
	
	/**
	 * 获取节点树,根节点和根节点的子节点
	 * @param isLocal 是否以本地节点为根节点　true 本地节点    false 水利部　
	 * @param isAll　是否为全部节点　true 全部节点　false 管理范围内节点
	 * @param checkedNodes 选中的节点
	 * @return
	 * @throws ServiceException
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public String getRootCheckedNodeTree(boolean isLocal, boolean isAll,List<GapOwnerConf> checkedNodes) throws ServiceException {
		StringBuffer nodeTreeData = new StringBuffer();
		try {
			NodeInfo localNode = nodeInfoDao.getLocalNode();
			NodeInfo root = nodeInfoDao.getNodeInfoByNodeCode(NodeInfoParam.MWR_NODEREGION_CODE);
			nodeTreeData.append("[");
			nodeTreeData.append("{");
			nodeTreeData.append("id:'").append(root.getId()).append("',");
			nodeTreeData.append("pId:'").append("").append("',");
			
			if ("1".equals(root.getHasGap())) {//如果
				nodeTreeData.append("name:'").append(root.getNodeName()+"(有网闸)").append("',");
			}else{
				nodeTreeData.append("name:'").append(root.getNodeName()).append("',");
			}
			
			//判断节点默认是否选中
			if(containProperty(checkedNodes, root.getNodeCode())){
				nodeTreeData.append("checked:").append(true).append(",");
			}
			
			nodeTreeData.append("nodeCode:'").append(root.getNodeCode()).append("',");
			if (!root.getId().equals(localNode.getId()) && !root.getPid().equals(localNode.getId())) {
				nodeTreeData.append("font:").append("{'color':'grey'}").append(",");
			} else {
				nodeTreeData.append("font:").append("{'color':'#428bca'}").append(",");
			}
			nodeTreeData.append("orgCode:'").append(root.getNodeCode().substring(0, 6)).append("',");
			
			if (root.getIsLocal().equals("1")) {
				nodeTreeData.append("icon:").append("_rs_image_path+\'/node1.png'").append(",");
			} else if (root.getPid().equals(localNode.getId())) {
				nodeTreeData.append("icon:").append("_rs_image_path+\'/node2.png'").append(",");
			}else{
				nodeTreeData.append("icon:").append("_rs_image_path+\'/node0.png'").append(",");
			}
			nodeTreeData.append("open:").append(true);
			nodeTreeData.append("}");
			List list = nodeInfoDao.getAllList(root.getId());
			for (Iterator<NodeInfo> iterator = list.iterator(); iterator.hasNext();) {
				NodeInfo vo = iterator.next();
				boolean checked = true;
				boolean isOpen = false;
				boolean isParent = false;
				if (Integer.parseInt(vo.getCont()) > 0 && isAll) {
					isParent = true;
				}
				nodeTreeData.append(",");
				nodeTreeData.append("{");
				nodeTreeData.append("id:'").append(vo.getId()).append("',");
				nodeTreeData.append("pId:'").append(vo.getPid()).append("',");
				
				if ("1".equals(vo.getHasGap())) {//如果
					nodeTreeData.append("name:'").append(vo.getNodeName()+"(有网闸)").append("',");
				}else{
					nodeTreeData.append("name:'").append(vo.getNodeName()).append("',");
				}
				
				nodeTreeData.append("nodeCode:'").append(vo.getNodeCode()).append("',");
				
				if (!vo.getId().equals(localNode.getId()) && !vo.getPid().equals(localNode.getId())) {
					nodeTreeData.append("font:").append("{'color':'grey'}").append(",");
				} else {
					nodeTreeData.append("font:").append("{'color':'#428bca'}").append(",");
				}
				nodeTreeData.append("orgCode:'").append(vo.getNodeCode().substring(0, 6)).append("',");
				nodeTreeData.append("type:'").append(1).append("',");
				
				//判断节点默认是否选中
				if(containProperty(checkedNodes, vo.getNodeCode())){
					nodeTreeData.append("checked:").append(checked).append(",");
				}
				
				
				nodeTreeData.append("open:").append(isOpen).append(",");
				if (vo.getIsLocal().equals("1")) {
					nodeTreeData.append("icon:").append("_rs_image_path+\'/node1.png'").append(",");
				} else if (vo.getPid().equals(localNode.getId())) {
					nodeTreeData.append("icon:").append("_rs_image_path+\'/node2.png'").append(",");
				}else{
					nodeTreeData.append("icon:").append("_rs_image_path+\'/node0.png'").append(",");
				}
				nodeTreeData.append("isParent:").append(isParent);
				nodeTreeData.append("}");
			}
		} catch (DaoException e) {
			throw new ServiceException("获取节点树失败", e);
		}
		nodeTreeData.append("]");
		return nodeTreeData.toString();
	}

	
	/**
	 * 判断列表GapOwnerConf中的gapuser属性值是否等于value
	 * @param ownerConfs
	 * @param value
	 * @return
	 */
	private boolean containProperty(List<GapOwnerConf> ownerConfs,String value){
		if (ownerConfs!=null && !ownerConfs.isEmpty()) {
			for (GapOwnerConf gapOwnerConf : ownerConfs) {
				if (value.equals(gapOwnerConf.getGapUser())) {
					return true;
				}
			}
		}
		return false;
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public String nodeTree(String id) throws ServiceException {
		StringBuilder nodeTreeData = new StringBuilder();
		List list;
		try {
			NodeInfo localNode = nodeInfoDao.getLocalNode();
			NodeInfo localDummyNode = nodeInfoDao.getLocalDummyNode("1".equals(NodeInfoParam.NODE_NET_TYPE)? "2" : "1");
			list = nodeInfoDao.getAllList(id);
			nodeTreeData.append("[");
			for (Iterator<NodeInfo> iterator = list.iterator(); iterator.hasNext();) {
				NodeInfo vo = iterator.next();
				nodeTreeData.append("{");
				nodeTreeData.append("id:'").append(vo.getId()).append("',");
				nodeTreeData.append("pId:'").append(vo.getPid()).append("',");
				nodeTreeData.append("name:'").append(vo.getNodeName()).append("',");
				nodeTreeData.append("orgCode:'").append(vo.getNodeCode().substring(0, 6)).append("',");
				nodeTreeData.append("netType:'").append(vo.getNetType()).append("',");
				if(vo.getNetType().equals(NodeInfoParam.NODE_NET_TYPE) ){
					 if (localNode != null && vo.getPid().equals(localNode.getId())) {
						 if(NodeInfoParam.isManaagerNode()){
								nodeTreeData.append("isEdit:'").append("1").append("',");
							}
						 nodeTreeData.append("font:").append("{'color':'#428bca'}").append(",");
					 }else{
						 nodeTreeData.append("isEdit:'").append("0").append("',");
						 nodeTreeData.append("font:").append("{'color':'grey'}").append(",");
					 }
					 if (vo.getIsLocal().equals("1")) {
							nodeTreeData.append("icon:").append("_rs_image_path+\'/node1.png'").append(",");
						} else if (localNode != null && vo.getPid().equals(localNode.getId())) {
							nodeTreeData.append("icon:").append("_rs_image_path+\'/node2.png'").append(",");
						}else{
							nodeTreeData.append("icon:").append("_rs_image_path+\'/node0.png'").append(",");
						}
					if ( vo.getId().equals(localNode.getId()) && NodeInfoParam.isManaagerNode()) {
							nodeTreeData.append("isAdd:'").append("1").append("',");
					} else {
							nodeTreeData.append("isAdd:'").append("0").append("',");
					}
				}else{
					if (localDummyNode != null && vo.getPid().equals(localDummyNode.getId())) {
						 nodeTreeData.append("isEdit:'").append("1").append("',");
						 nodeTreeData.append("font:").append("{'color':'#428bca'}").append(",");
						 nodeTreeData.append("icon:").append("_rs_image_path+\'/node2.png'").append(",");
					 }else{
						 nodeTreeData.append("isEdit:'").append("0").append("',");
						 nodeTreeData.append("font:").append("{'color':'grey'}").append(",");
						nodeTreeData.append("icon:").append("_rs_image_path+\'/node0.png'").append(",");
					 }
					if(localDummyNode != null && vo.getId().equals(localDummyNode.getId()) && NodeInfoParam.isManaagerNode()){
						nodeTreeData.append("isAdd:'").append("1").append("',");
					}else{
						nodeTreeData.append("isAdd:'").append("0").append("',");
					}
				}
				nodeTreeData.append("type:'").append(2).append("',");
				nodeTreeData.append("nocheck:").append(true).append(",");
				nodeTreeData.append("checked:").append(false).append(",");
				nodeTreeData.append("open:").append(false).append(",");
				nodeTreeData.append("}");
				if (iterator.hasNext())
					nodeTreeData.append(",");
			}
			nodeTreeData.append("]");
		} catch (DaoException e) {
			throw new ServiceException("获取节点树失败", e);
		}
		return nodeTreeData.toString();
	}

	/**
	 * 验证属性唯一性
	 * @param property　属性
	 * @param newValue	新值
	 * @param oldValue　旧值
	 * @param orgCode　行政区代码
	 * @return
	 * @throws ServiceException
	 */
	public boolean isPropertyUnique(String property, String newValue, String oldValue, String orgCode)
			throws ServiceException {
		try {
			return nodeInfoDao.isPropertyUnique(property, newValue, oldValue, orgCode);
		} catch (DaoException e) {
			throw new ServiceException("验证属性唯一性失败", e);
		}
	}

	/**
	 * 获取与此节点进行数据交换的全部子节点列表
	 * @param nodeId 当前节点ID
	 * @return
	 * @throws ServiceException
	 */
	public List<NodeInfo> getAllExchNodeList(String nodeId) throws ServiceException {
		try {
			return nodeInfoDao.getAllExchNodeList(nodeId);
		} catch (DaoException e) {
			throw new ServiceException("获取全部节点失败", e);
		}
	}

	public boolean nodeExitsByRegionCode(String checkNodeExitsByRegionCode) throws ServiceException {
		try {
			return nodeInfoDao.nodeExitsByRegionCode(checkNodeExitsByRegionCode);
		} catch (DaoException e) {
			throw new ServiceException("验证当前行政区对应的节点是否已经纯在", e);
		}
	}
/**
 * 获取节点进行数据交换的节点列表
 * @param nodeId
 * @return
 * @throws ServiceException
 */
	public List<NodeInfo> getAllLocalExchNodeList(String nodeId)  throws ServiceException {
		try {
			return nodeInfoDao.getAllExchNodeListByNodeId(nodeId);
		} catch (DaoException e) {
			throw new ServiceException("获取节点进行数据交换的节点列表失败", e);
		}
	}

	public List<NodeInfo> getListByNetType(String netType) throws ServiceException {
		try {
			return nodeInfoDao.getListByNetType(netType);
		} catch (DaoException e) {
			throw new ServiceException("获取节点数据失败", e);
		}
	}

	public NodeInfo getRootNodeInfoByNodeCode(String nodeCode, String netType) throws ServiceException {
		try {
			return nodeInfoDao.getRootNodeInfoByNodeCode(nodeCode,netType);
		} catch (DaoException e) {
			throw new ServiceException("获取节点数据失败", e);
		}
	}

	public NodeInfo getRootNodeInfoByPidAndNetType(String mwrNodePid,
			String netType) throws ServiceException {
		try {
			return nodeInfoDao.getRootNodeInfoByPidAndNetType(mwrNodePid,netType);
		} catch (DaoException e) {
			throw new ServiceException("获取节点数据失败", e);
		}
	}
	/**
	 *获取本地虚拟管理节点
	 * @param netType
	 * @return
	 * @throws ServiceException
	 */
	public NodeInfo getLocalDummyNode(String netType) throws ServiceException {
		try {
			return nodeInfoDao.getLocalDummyNode(netType);
		} catch (DaoException e) {
			throw new ServiceException("获取节点数据失败", e);
		}
	}

	public NodeInfo getNodeByNodeCode(String nodeCode) throws ServiceException {
		try {
			return nodeInfoDao.getNodeByNodeCode(nodeCode);
		} catch (DaoException e) {
			throw new ServiceException("获取节点数据失败", e);
		}
	}
	public List<NodeInfo> getNodeListByNodeCode(String[] nodeCodes) throws ServiceException {
		try {
			return nodeInfoDao.getNodeListByNodeCode(nodeCodes);
		} catch (DaoException e) {
			throw new ServiceException("获取节点数据失败", e);
		}
	}

	/**
	 * 是否存在参数 registryUrl地址
	 * @param registryUrl 前端参数“验证地址”
	 * @return true：存在相同的地址 false：不存在
	 * @throws ServiceException 
	 */
	public boolean isSameUrl(String registryUrl) throws ServiceException {
		try {
			return nodeInfoDao.isSyncUrlExist(registryUrl);
		} catch (DaoException e) {
			throw new ServiceException("存在相同的url地址", e);
		}
	}
}
